// static/js/contract-edit.js
document.addEventListener('DOMContentLoaded', function() {
    // 根据合同类型显示/隐藏相关字段
    const contractTypeSelect = document.getElementById('contractType');
    if (contractTypeSelect) {
        contractTypeSelect.addEventListener('change', updateFormFields);
        updateFormFields(); // 初始加载时执行一次
    }
});

function updateFormFields() {
    const contractType = document.getElementById('contractType').value;

    // 隐藏所有动态部分
    document.querySelectorAll('.form-section[th\\:if]').forEach(section => {
        section.style.display = 'none';
    });

    // 显示当前合同类型对应的部分
    const sectionToShow = document.querySelector(`.form-section[th\\:if*="'${contractType}'"]`);
    if (sectionToShow) {
        sectionToShow.style.display = 'block';
    }
}

function uploadFile() {
    const fileInput = document.getElementById('fileInput');
    const contractId = document.querySelector('input[name="contractId"]').value;

    if (fileInput.files.length === 0) {
        alert('请选择要上传的文件');
        return;
    }

    const formData = new FormData();
    formData.append('file', fileInput.files[0]);

    fetch(`/contract/upload-attachment/${contractId}`, {
        method: 'POST',
        body: formData
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('上传失败');
            }
            return response.json();
        })
        .then(data => {
            // 刷新页面以显示新上传的附件
            window.location.reload();
        })
        .catch(error => {
            alert(error.message);
            console.error('Error:', error);
        });
}

function deleteAttachment(button) {
    if (!confirm('确定要删除此附件吗？')) {
        return;
    }

    const contractId = button.getAttribute('data-contract-id');
    const attachmentId = button.getAttribute('data-attachment-id');

    fetch(`/contract/delete-attachment/${contractId}/${attachmentId}`, {
        method: 'DELETE'
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('删除失败');
            }
            // 刷新页面以更新附件列表
            window.location.reload();
        })
        .catch(error => {
            alert(error.message);
            console.error('Error:', error);
        });
}